<?php
defined( 'BASEPATH' ) or exit( 'No direct script access allowed' );
class MY_Controller extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        
        // 开启缓存区
        for($level = ob_get_level(); $level > 0; -- $level)
        {
            ob_end_clean();
        }
        ob_start();
        
        // 加载公共配置
        if (! is_file( $file = FCPATH . 'conf/common.php' ))
        {
            show_error( 'The configuration file data/config.php does not exist.' );
        }
        include ($file);
        
        // 存储文件上传路径到控制器属性，以便子类可以访问
        if (isset( $upload_folder ))
        {
            $this->upload_folder = $upload_folder;
        }
        
        // 判断手机访问
        if ($this->is_wap())
        {
            header( "location:" . base_url( 'wap.php' ) );
        }
        
        // 加载语言文件
        switch ($this->uri->logic_group)
        {
            case 'en' :
                $this->load->language( array (
                        'page',
                        'field' 
                ), 'en_us' );
                break;
            default :
                $this->load->language( array (
                        'page',
                        'field' 
                ), 'zh_cn' );
        }
        
        // 加载自定义的数据库访问
        if (! is_file( $file = APPPATH . 'include/MyPDO.class.php' ))
        {
            show_error( 'The class file MyPDO.class.php does not exist.' );
        }
        include ($file);
        $this->pdo = MyPDO::get_instance();
        // 数据库配置
        if (! isset( $active_group ))
        {
            show_error( 'You have not specified a database connection group via $active_group in your config/database.php file.' );
        }
        elseif (! isset( $db[$active_group] ))
        {
            show_error( 'You have specified an invalid database connection group (' . $active_group . ') in your config/database.php file.' );
        }
        if (! $this->pdo->connect( $db[$active_group] ))
        {
            exit();
        }
        
        // 标识客户端
        if (PHP_SAPI != 'cli' && ! isset( $_COOKIE['CLIENT_ID'] ))
        {
            $client_id = md5( $_SERVER['REQUEST_TIME_FLOAT'] );
            $_COOKIE['CLIENT_ID'] = $client_id;
            setcookie( 'CLIENT_ID', $client_id, 2147483647, '/' );
        }
        
        // 加载日志
        if (! is_file( $file = APPPATH . 'include/MyLog.class.php' ))
        {
            show_error( 'The class file MyLog.class.php does not exist.' );
        }
        include ($file);
        $this->mylog = MyLog::get_instance( array (
                'table_name_id' => 'client_log_id',
                'table_name_request' => 'client_log_request',
                'table_name_msg' => 'client_log_msg',
                'flag' => 255 
        ) );
        
        // 加载自定义会话
        if (! is_file( $file = APPPATH . 'include/MySession.class.php' ))
        {
            show_error( 'The class file MySession.class.php does not exist.' );
        }
        include ($file);
        
        // 是否ajax请求（所有处理ajax请求的接口均位于ajax目录下）
        $is_ajax = strtolower( $this->router->directory ) == 'ajax/' ? true : false;
        
        // 根据不同请求，加载不同类
        if ($is_ajax)
        {
            // 加载ajax返回器
            $this->load->library( 'JsonResult', array (
                    'callback' => $this->input->get( 'callback' ),
                    'debug' => true 
            ), 'rs' );
        }
        else
        {
            //
        }
        
        // 判断登陆
        $request = $this->router->directory . $this->router->class . '/' . $this->router->method;
        $request = ltrim( strtolower( $request ), '/' );
        $this->request = $request;
        $this->load->vars( 'request', $request );
        // echo $request;
        if (in_array( $request, $this->config->item( 'login_include' ) ))
        {
            //开启会话
            MySession::get_instance();
            
            // 加载会员辅助
            if (! is_file( $file = APPPATH . 'include/MemberHelper.class.php' ))
            {
                show_error( 'The class file MemberHelper.class.php does not exist.' );
            }
            include ($file);
            
            // 请求需要验证登录
            if (! MemberHelper::check_login( true ))
            {
                if ($is_ajax)
                {
                    $this->rs->err( 3 );
                }
                else
                {
                    header( "location:" . site_url( "member/login" ) );
                }
                exit();
            }
            $this->member = $_SESSION['member'];
            $this->load->vars( 'member', $this->member );
            
            // 根据“控制器/方法”判断用户权限（已登录）
            if (! in_array( $request, $this->config->item( 'permission_exclude' ) ))
            {
                if (! $this->check_permission())
                {
                    if ($is_ajax)
                    {
                        $this->rs->err( 4 );
                    }
                    else
                    {
                        header( "location:" . site_url( "member/index" ) );
                    }
                    exit();
                }
            }
        }
        
        // 加载菜单（已登录且有访问权限）
        if (! $is_ajax)
        {
            // $this->load_menu();
        }
    }
    function test()
    {
        echo 'This is a test function in controller.';
    }
    protected function check_permission($uri = null)
    {
        return true;
    }
    private function is_wap()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset( $_SERVER['HTTP_X_WAP_PROFILE'] ))
        {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset( $_SERVER['HTTP_VIA'] ))
        {
            // 找不到为flase,否则为true
            return stristr( $_SERVER['HTTP_VIA'], "wap" ) ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset( $_SERVER['HTTP_USER_AGENT'] ))
        {
            $clientkeywords = array (
                    'nokia',
                    'sony',
                    'ericsson',
                    'mot',
                    'samsung',
                    'htc',
                    'sgh',
                    'lg',
                    'sharp',
                    'sie-',
                    'philips',
                    'panasonic',
                    'alcatel',
                    'lenovo',
                    'iphone',
                    'ipod',
                    'blackberry',
                    'meizu',
                    'android',
                    'netfront',
                    'symbian',
                    'ucweb',
                    'windowsce',
                    'palm',
                    'operamini',
                    'operamobi',
                    'openwave',
                    'nexusone',
                    'cldc',
                    'midp',
                    'wap',
                    'mobile' 
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match( "/(" . implode( '|', $clientkeywords ) . ")/i", strtolower( $_SERVER['HTTP_USER_AGENT'] ) ))
            {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset( $_SERVER['HTTP_ACCEPT'] ))
        {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos( $_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml' ) !== false) && (strpos( $_SERVER['HTTP_ACCEPT'], 'text/html' ) === false || (strpos( $_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml' ) < strpos( $_SERVER['HTTP_ACCEPT'], 'text/html' ))))
            {
                return true;
            }
        }
        return false;
    }
}